package com.ty.zls.task;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;

import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.ty.zls.activity.LoginActivity;
import com.ty.zls.adapter.ArreageAdapter;
import com.ty.zls.bean.Account;
import com.ty.zls.bean.Constants;
import com.ty.zls.util.CommonUtil;
import com.ty.zls.util.HttpUtil;
import com.ty.zls.util.StrogeUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 抄表数据请求
 */
public class ArreageTask extends AsyncTask<Map<String, String>, Void, Map<String, Object>> implements View.OnClickListener {

    private Activity context;
    private ArreageAdapter adapter;
    private QMUIEmptyView emptyView;
    private SwipeToLoadLayout layout;
    private View emptyViewContianer;

    public ArreageTask(QMUIEmptyView emptyView, Context context, ArreageAdapter adapter, SwipeToLoadLayout layout) {
        this.context = (Activity) context;
        this.adapter = adapter;
        this.emptyViewContianer = emptyView;
        this.emptyView = emptyView;
        this.layout = layout;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        emptyView.show(true);
    }

    @Override
    protected Map<String, Object> doInBackground(Map<String, String>... maps) {
        Map<String, Object> data = new HashMap<>();
        try {
            JSONObject result = HttpUtil.post(maps[0], HttpUtil.ARREAGE);
            int code = result.optInt("code");
            data.put("code", code);
            data.put("msg", result.optString("msg"));
            data.put("result", result);
        } catch (Exception e) {
            data.put("code", Constants.ERROR_CODE);
        }
        return data;
    }

    @Override
    protected void onPostExecute(Map<String, Object> map) {
        super.onPostExecute(map);
        String title = "";
        final Integer code = (Integer) map.get("code");
        if (Constants.ERROR_CODE.equals(code)) {
            if (!CommonUtil.isNetworkAvailable(context)) {
                title = "请检查网络是否连接";
            } else {
                title = "请稍后重试";
            }
            layout.setVisibility(View.GONE);
            emptyViewContianer.setVisibility(View.VISIBLE);
            emptyView.show(false, "请求失败", title, "点击重试", this);
        } else if (Constants.FAIL_CODE.equals(code)) {
            layout.setVisibility(View.GONE);
            emptyViewContianer.setVisibility(View.VISIBLE);
            emptyView.show(false, "请求失败", (String) map.get("msg"), "点击重试", this);
        } else if (Constants.TOKEN_VAILD.equals(code)) {
            //返回登录
            StrogeUtil.rmToken(context);
            context.startActivity(new Intent(context, LoginActivity.class));
            context.finish();
            return;
        } else if (Constants.SUCCESS_CODE.equals(code)) {
            try {
                addAccount((JSONObject) map.get("result"));
                adapter.notifyDataSetChanged();
                return;
            } catch (JSONException e) {
                emptyViewContianer.setVisibility(View.VISIBLE);
                layout.setVisibility(View.GONE);
                emptyView.show(false, "请求失败", e.getMessage(), "点击重试", this);

            }
        }
    }


    /**
     * 添加
     */
    private void addAccount(JSONObject result) throws JSONException {
        JSONObject object = result.optJSONObject("accounts");
        if (object != null) {
            if (adapter.getDatas().size() != object.optInt("total")) {
                adapter.setTotal(object.optInt("total"));
                adapter.setPageNum(adapter.getPageNum() + 1);
                JSONArray rows = object.optJSONArray("rows");
                for (int i = 0; i < rows.length(); i++) {
                    JSONObject accountObject = rows.optJSONObject(i);
                    Account account = new Account(accountObject.getString("id"), accountObject.optString("name")
                            , accountObject.optString("tel"), accountObject.optString("preSort"), accountObject.optString("sort")
                            , accountObject.optString("arreage")
                    );
                    account.setBalance(accountObject.optString("balance"));
                    account.setArea(accountObject.optString("area"));
                    adapter.getDatas().add(account);
                }
            }
        }

        if(adapter.getDatas().size() == 0) {
            emptyView.show(false, "暂无数据", "没有发现相关欠费用户", "点击重试", this);
        }
    }


    private Map<String, String> request = new HashMap<>();

    @Override
    public void onClick(View v) {
        String token = StrogeUtil.getStringFraomPs(context, StrogeUtil.user, StrogeUtil.token);
        request.put("token", token);
        request.put("pageNum", String.valueOf(adapter.getPageNum()));
        request.put("pageSize", String.valueOf(adapter.getPageSize()));
        new ArreageTask(emptyView, context, adapter, layout).execute(request);
    }
}
